package com.shiroha.user.service.impl;

import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.shiroha.common.enums.GroupRole;
import com.shiroha.common.exception.BadRequestException;
import com.shiroha.common.pojo.dto.ChatGroupDTO;
import com.shiroha.common.pojo.dto.GroupMemberDTO;
import com.shiroha.user.mapper.ChatGroupMapper;
import com.shiroha.user.pojo.ChatGroup;
import com.shiroha.user.pojo.GroupMember;
import com.shiroha.user.service.IChatGroupService;
import com.shiroha.user.service.IGroupMemberService;
import lombok.AllArgsConstructor;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

import static com.shiroha.user.pojo.table.Tables.*;

@Service
@AllArgsConstructor
public class ChatGroupServiceImpl extends ServiceImpl<ChatGroupMapper, ChatGroup> implements IChatGroupService {

    private final IGroupMemberService groupMemberService;

    /**
     * 根据 groupId 获取指定群组的详细信息
     *
     * @param groupId 群组ID
     * @return DTO对象
     */
    @Override
    public ChatGroupDTO getGroupByGroupId(Long groupId) {
        return this.mapper.selectChatGroupByGroupId(groupId);
    }

    /**
     * 创建群组
     * @param leaderId 群主ID
     * @param chatGroupDTO DTO对象
     * @return 是否创建成功
     */
    @Override
    @Transactional
    public boolean createGroup(UUID leaderId, ChatGroupDTO chatGroupDTO) {
        if(Arrays.stream(chatGroupDTO.getMemberIds())
                .filter(memberId -> memberId.equals(leaderId))
                .toArray().length > 0) {
            throw new BadRequestException("成员ID列表不能包含群主");
        }

        // 插入 chat_group 表
        ChatGroup chatGroup = new ChatGroup();
        chatGroup.setName(chatGroupDTO.getName());
        chatGroup.setAvatar(chatGroupDTO.getAvatar());
        chatGroup.setDescription(chatGroupDTO.getDescription());
        this.save(chatGroup);

        // 创建新列表保存群主ID和成员ID
        List<UUID> memberIds = new  ArrayList<>();
        memberIds.add(leaderId);
        memberIds.addAll(List.of(chatGroupDTO.getMemberIds()));

        List<GroupMember> groupMembers = memberIds.stream()
                .map(groupMemberId -> GroupMember.builder()
                        .groupId(chatGroup.getId())
                        // 列表第一个元素是群主ID
                        .role(groupMemberId.equals(memberIds.getFirst()) ? GroupRole.GROUP_LEADER : GroupRole.GROUP_MEMBER)
                        .userId(groupMemberId)
                        .build()
                )
                .toList();
        return groupMemberService.saveBatch(groupMembers);
    }

    /**
     * 获取用户加入的全部群组
     *
     * @param userId 用户ID
     * @return 群组列表
     */
    @Override
    @Caching(
            cacheable = @Cacheable(cacheNames = "chat_group", key = "#userId.toString()")
    )
    public List<ChatGroupDTO> getAllGroupsByUserId(UUID userId) {
        return this.mapper.selectChatGroupListByUserId(userId);
    }

    /**
     * 解散群聊
     *
     * @param userId  请求者ID
     * @param groupId 群组ID
     */
    @Override
    public boolean deleteGroup(UUID userId, Long groupId) {
        return this.mapper.deleteGroup(userId, groupId) > 0;
    }
}
